package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * CTassName: UploadController
 * Package: com.itheima.controller
 * Description:
 *
 * @Author xw
 * @Create 2023/11/6 13:10
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {
        log.info("文件上传：{},{},{}", username, age, image);

        // 获取原始文件名
        // String originalFilename = image.getOriginalFilename();

        // 将文件存储在服务器的磁盘目录
        // image.transferTo(new File("E:/images/" + originalFilename));

        // 构建新的文件名
//        int i = originalFilename.lastIndexOf(".");
//        log.info("originalFilename.lastIndexOf(\".\");------> 结果{}",i);
//
//
//        log.info("originalFilename.substring(i);------> 结果{}",substring);

        // 优化
        /*String extname = originalFilename.substring(originalFilename.lastIndexOf("."));//文件扩展名
        log.info("originalFilename.substring(i);------> 结果{}",extname);


        //随机名+文件扩展名
        String newFileName = UUID.randomUUID().toString()+ extname;

        //将文件存储在服务器的磁盘目录
        File file = new File("D:\\image\\" + newFileName);
        image.transferTo(file);*/


        // 上传到 阿里云

        //调用阿里云OSS工具类，将上传上来的文件存入阿里云
        String url = aliOSSUtils.upload(image);


        //将图片上传完成后的url返回，用于浏览器回显展示
        return Result.success(url);

    }

}
